package com.morehair.service.admin.impl;

import com.github.pagehelper.PageInfo;
import com.morehair.bean.bo.admin.AdReq;
import com.morehair.bean.bo.admin.BaseReq;
import com.morehair.bean.pojo.Ad;
import com.morehair.bean.pojo.AdExample;
import com.morehair.bean.vo.admin.BaseData;
import com.morehair.mapper.AdMapper;
import com.morehair.service.admin.AdService;
import com.morehair.utils.AdPageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Author: DLX
 * @Date: 2021/6/5 10:55
 * @Description:
 **/
@Service
@Transactional
public class AdServiceImpl implements AdService {

    @Autowired
    AdMapper adMapper;

    @Override
    public BaseData<Ad> query(BaseReq baseReq) {
        AdPageHelper.startPage(baseReq);

        AdReq adReq = (AdReq) baseReq;
        String name = adReq.getName();
        String content = adReq.getContent();

        AdExample adExample = new AdExample();
        AdExample.Criteria criteria = adExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (content != null && !"".equals(content)) {
            criteria.andContentLike("%" + content + "%");
        }
        List<Ad> ads = adMapper.selectByExample(adExample);
        // total
        PageInfo<Ad> adPageInfo = new PageInfo<>(ads);
        long total = adPageInfo.getTotal();

        return BaseData.ok(ads, total);
    }

    @Override
    public Ad create(Ad ad) {
        Date date = new Date();
        Date addTime = date;
        Date updateTime = date;
        ad.setAddTime(addTime);
        ad.setUpdateTime(updateTime);
        int insert = adMapper.insertSelective(ad);
        if (insert == 1) {
            Ad newAd=adMapper.selectNewAd();
            return newAd;
        }
        return null;
    }

    @Override
    public Ad adUpdate(Ad ad) {
        Date date = new Date();
        Date updateTime = date;
        ad.setUpdateTime(updateTime);
        int i = adMapper.updateByPrimaryKeySelective(ad);
        if (i == 1) {
            Ad newAd = adMapper.selectByPrimaryKey(ad.getId());
            return newAd;
        }
        return null;
    }

    @Override
    public int adDelete(Ad ad) {
        ad.setDeleted(true);
        int affectedRows = adMapper.updateByPrimaryKeySelective(ad);
        if (affectedRows == 1) {
            return 200;
        }
        return 404;
    }


}
